const { Op } = require("sequelize");
const sequelize = appRequire('db');

const artPaintingModel = appRequire('models/artPainting');
const collectModel = appRequire('models/collect');
const thisRequest = require('sync-request');

// 导出对象，供其它模块调用
module.exports = {
    list,
    detail,
    preview,
    downLoad,
    downLoadSingle,
    nowMonthList,
    videoAddNum,
    totalNum,
};

//收录课件总数
async function totalNum(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let course = await artPaintingModel.count()
    returnData.data = Common.clone(course)
    request.json(returnData)
}

async function list(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, [], request);
    if (checkResult == false) return;

    /*url = "https://albumgroup.m.qq.com/story?groupId=cJ0VIXELSDAWQaYr&page=0&size=3"
    var res = thisRequest('GET', url, {
        json: {},
        headers: {
            "Content-Type": "application/json; charset=utf-8",
            "key": "cd4e7382-e189-4f5b-b87a-53751cb062a8",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x6309080f) XWEB/9105"
        }
    });
    var body2 = res.getBody();
    if(body2.success && body2.content){

    }
    console.log(JSON.parse(body2))*/

    let params = {}
    let orders = [['createdAt', 'DESC']]

    if (postData.type) {
        if (postData.type == "全部") {
            orders = [['createdAt', 'DESC'], ['downLoadNum', 'DESC']]
        } else if (postData.type == "最热") {
            orders = [['downLoadNum', 'DESC']]
        } else {
            params.class = postData.type
        }
    }

    if (postData.searchText) {
        params[Op.or] = [
            { nameZh: { [Op.like]: '%' + postData.searchText + '%' } },
            { extraNameZh: { [Op.like]: '%' + postData.searchText + '%' } },
            { nameEn: { [Op.like]: '%' + postData.searchText + '%' } },
            { author: { [Op.like]: '%' + postData.searchText + '%' } },
        ]
    }
    if (postData.isNice) params.isNice = postData.isNice

    let course = await artPaintingModel.findAndCountAll({
        where: params,
        order: orders,
        limit: postData.pageSize,
        offset: postData.pageSize * (postData.pageNum - 1),
        attributes: ["objectId", "imageUrl", "nameZh", "author", "downLoadNum", "createdAt", "images", "type", "dominantColor", "dominantColor2"]
    })
    course = Common.clone(course)

    for (let item of course.rows) {
        item.imageUrl = item.imageUrl + "?imageMogr2/format/webp/thumbnail/!10p"
    }

    /*if (postData.pageNum <= 15) {
        let adunits = [
            '8775b673aa03531a', 'b16cdf1f2f6716e1', 'edb259efe26a4b70', 'ef8c19ca83b7eca3', '5be76710956b1600',
            'a23e447cd9f2ab32', 'fa595befa9b93df1', '1be255d2a86bbab1', 'd89c601f5dac62c4', '5e2bd086429ab73c',
            '09d5884f889b65b5', 'c9d97415fec0bfa8', 'af2f86428bc31114', 'b411c803f91fec45', '5df741c5427ea43d',
        ]
        course.rows.push({
            classDesc: '广告',
            id: adunits[postData.pageNum - 1]
        })
    }*/

    returnData.maxCount = course.count
    returnData.maxPage = Math.ceil(course.count / postData.pageSize)
    returnData.data = course.rows
    request.json(returnData)
}


//当前月份的精选内容
async function nowMonthList(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, [], request);
    if (checkResult == false) return;

    let year = new Date().getFullYear()
    let month = new Date().getMonth() + 1 < 10 ? '0' + (new Date().getMonth() + 1) : new Date().getMonth() + 1
    let maxDay = new Date(year, month, 0).getDate()

    let params = {
        isNice: true
    }

    let course = await artPaintingModel.findAndCountAll({
        where: params,
        order: [['createdAt', 'DESC']],
        limit: 20
    })
    course = Common.clone(course)
    for (let item of course.rows) {
        item.imageUrl = item.imageUrl + "?imageMogr2/format/webp/thumbnail/!10p"
    }

    returnData.maxCount = course.count
    returnData.maxPage = Math.ceil(course.count / postData.pageSize)
    returnData.data = course.rows
    request.json(returnData)
}

//画作详情
async function detail(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, ['objectId'], request);
    if (checkResult == false) return;

    let course = await artPaintingModel.findOne({
        where: {
            objectId: postData.objectId
        },
        //attributes: ["objectId", "number", "price", "title", "desc", "content", "downLoadNum", "classDesc", "tags", "images", "videoUrl", "createdAt"]
    })
    course = Common.clone(course)
    course.collect = 0
    if (postData.uid) { //登陆获取是否收藏
        result2 = await collectModel.collect.findOne({
            where: {
                artPaintingId: course.objectId,
                userId: postData.uid,
            }
        })
        if (result2) course.collect = 1
    }

    //查看数量增加
    await artPaintingModel.update({ downLoadNum: course.downLoadNum + 1 }, {
        where: {
            objectId: postData.objectId
        },
    })

    if (course.images && course.images.length > 0) {
        /*let _images = []
        for (let image of course.images) {
            _images.push(image + "?imageMogr2/format/webp")
        }
        course.images = _images*/
    }

    returnData.data = course
    request.json(returnData)
}

//单个文件下载
async function downLoad(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, ['objectId'], request);
    if (checkResult == false) return;

    let course = await artPaintingModel.findOne({
        where: {
            objectId: postData.objectId
        },
    })
    course = Common.clone(course)

    if (course && course.fileUrls && course.fileUrls.length > 0) {
        if (course.fileUrls[postData.index] && course.fileUrls[postData.index].fileUrl) {
            returnData.data = course.fileUrls[postData.index].fileUrl
            //下载数量增加
            await artPaintingModel.update({ downLoadNum: course.downLoadNum + 1 }, {
                where: {
                    objectId: postData.objectId
                },
            })
        } else {
            returnData.code = 0
            returnData.msg = "未上传文件"
        }
    } else {
        returnData.code = 0
        returnData.msg = "未上传文件"
    }
    request.json(returnData)
}

//下载合集中的单个
async function downLoadSingle(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, ['objectId'], request);
    if (checkResult == false) return;

    let course = await artPaintingModel.findOne({
        where: {
            objectId: postData.objectId
        },
    })
    course = Common.clone(course)

    if (course && course.fileUrls && course.fileUrls.length > 0) {
        if (course.type == "合集") {
            if (course.fileUrls[postData.index] && course.fileUrls[postData.index].fileUrl) {
                returnData.data = course.fileUrls[postData.index].fileUrl
                //下载数量增加
                await artPaintingModel.update({ downLoadNum: course.downLoadNum + 1 }, {
                    where: {
                        objectId: postData.objectId
                    },
                })
            } else {
                returnData.code = 0
                returnData.msg = "未上传文件"
            }

        } else {
            returnData.code = 0
            returnData.msg = "单个不支持使用合集下载"
        }
    } else {
        returnData.code = 0
        returnData.msg = "未上传文件"
    }
    request.json(returnData)
}

async function preview(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, ['objectId'], request);
    if (checkResult == false) return;

    let course = await artPaintingModel.findOne({
        where: {
            objectId: postData.objectId
        },
    })
    course = Common.clone(course)
    if (course && course.fileUrls && course.fileUrls.length > 0) {
        returnData.data = course.fileUrls[postData.index].fileUrl + '?ci-process=doc-preview&dstType=html'
    } else {
        returnData.code = 0
        returnData.msg = "未上传文件"
    }
    request.json(returnData)
}

//增加视频点击数
async function videoAddNum(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, ['objectId'], request);
    if (checkResult == false) return;

    let course = await artPaintingModel.findOne({
        where: {
            objectId: postData.objectId
        },
    })
    course = Common.clone(course)

    await artPaintingModel.update({ downLoadNum: course.downLoadNum + 1 }, {
        where: {
            objectId: postData.objectId
        },
    })

    request.json(returnData)
}